import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, Alert, Modal} from 'antd';
import {
    FORM_OPTIONS,
    TABLE,
    PAGINATION_OPTIONS,
    PAGE,
    COMMON_TABLE_QUERY_FAIL_TEXT,
    COMMON_TABLE_EMPTY_TEXT,
    ROWSELECTION_FIXED_COLUMN_WIDTH
} from '../constants';
import TextInput from 'Shared/components/TextInput';
import SearchSelect from 'Shared/components/SearchSelect';
import {conventSorter} from './utils';
import styles from './style.css';
import WrappedTag from '../common/WrappedTag';
import {getPCs, getPCSimple} from './api';
import {injectIntl} from './intl';
import {productCategoryType} from '../Enum';
import {conventEnumValueToString} from '../utils';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
class ProductCategorySelectPanel extends PureComponent {
    state = {
        keys: [],
        rows: [],
        code: '',
        name: '',
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        showPanel: false,
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    };
    onQuery = condition => {
        this.setState({isFetching: true});
        getPCs({
            ...condition,
            type: productCategoryType.车型,
        })
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: EMPTY_OBJECT,
                        message: res.message
                    });
            });
    }

    onSearch = query => getPCSimple({
        query,
        type: productCategoryType.车型,
    })
    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            name: this.state.name,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }
    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onChangeRadio = (keys, rows) => {
        this.setState({
            keys,
            rows
        });
    }
    onCloseTag = () => {
        this.setState({
            keys: EMPTY_ARRAY,
            rows: EMPTY_ARRAY
        });
    }
    onSubmit = () => {
        this.onCancel();
        if(this.state.rows.length)
            this.props.onSelect(this.state.rows[0], this.props.id);
    }
    onCancel = () => {
        this.setState({
            keys: [],
            rows: [],
            code: '',
            name: '',
            isFetching: false,
            data: {},
            message: '',
            pageIndex: PAGE.index,
            pageSize: PAGE.smallSize,
            currentCondition: {},
            showPanel: false,
        });
    }
    onSelectSearch = data => {
        this.props.onSelect(data, this.props.id);
    }
    render() {
        const {code, name, isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'productCategorySelectPanel.columns.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'productCategorySelectPanel.name',
                    defaultMessage: '名称'
                }),
                dataIndex: 'name',
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'productCategorySelectPanel.type',
                    defaultMessage: '类型'
                }),
                dataIndex: 'type',
                render: text => conventEnumValueToString(productCategoryType, text)
            },
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const onRow = record => ({
            onDoubleClick: () => {
                this.onCancel();
                // 双击选中
                this.props.onSelect(record, this.props.id);
            }
        });
        const rowSelection = {
            type: 'radio',
            fixed: true,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH,
            onChange: this.onChangeRadio,
            selectedRowKeys: this.state.keys,
        };
        const selectTag = (<span>{this.props.intl.formatMessage({
            id: 'productCategorySelectPanel.selectTag',
            defaultMessage: '，已选择'
        })} {this.state.rows.map(tag =>
            <WrappedTag key={tag.id} id={tag.id} closable onClose={this.onCloseTag}>
                {tag.name}
            </WrappedTag>)}</span>);
        const alertMessage = (
            <Row>
                <Col span={18}><span>{this.props.intl.formatMessage({
                    id: 'productCategorySelectPanel.alertMessage',
                    defaultMessage: '可以双击行选择'
                })}</span>{this.state.rows.length ? selectTag : ''}</Col>
                <Col span={6} className="col-align-right">
                    <Button type="primary" size="small" onClick={this.onSubmit}>{this.props.intl.formatMessage({
                        id: 'productCategorySelectPanel.btn.confirm',
                        defaultMessage: '确认'
                    })}</Button>
                </Col>
            </Row>);
        return (
            <div>
                <SearchSelect
                    value={this.props.value}
                    placeholder={this.props.intl.formatMessage({
                        id: 'productCategorySelectPanel.searchSelect.placeholder',
                        defaultMessage: '请输入车型名称或编号进行查询'
                    })}
                    onSelect={this.onSelectSearch}
                    onSearch={this.onSearch}
                    keyIndex="id"
                    labelMap={d => `(${d.code})${d.name}`}
                    onClickSearchBtn={this.showPanel} />
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'productCategorySelectPanel.modal.title',
                        defaultMessage: '车型查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.onCancel}>
                    <Row className="form-standard operation-buttons">
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'productCategorySelectPanel.code',
                                    defaultMessage: '编号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput name="code" value={code}
                                    onPressEnter={this.handleFilterPressEnter} onBlur={this.onChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'productCategorySelectPanel.name',
                                    defaultMessage: '名称'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput name="name" value={name}
                                    onPressEnter={this.handleFilterPressEnter} onBlur={this.onChange} />
                            </FormItem>
                        </Col>
                        <Col
                            span={8}
                            className={styles.selectPanelBtn}>
                            <Button type="primary" onClick={this.onClickSearchBtn}>
                                {this.props.intl.formatMessage({
                                    id: 'productCategorySelectPanel.btn.query',
                                    defaultMessage: '查询'
                                })}
                            </Button>
                        </Col>
                    </Row>
                    <Divider className={styles.divider} />
                    <Alert className={styles.alertMargin} type="info" message={alertMessage} showIcon />
                    <Table
                        className={`white-space-nowrap ${styles.tableCursor}`}
                        rowKey="id"
                        dataSource={data.content || EMPTY_ARRAY}
                        columns={columns}
                        onRow={onRow}
                        loading={isFetching}
                        pagination={pagination}
                        onChange={this.handleTableChange}
                        rowSelection={rowSelection}
                        {...TABLE}
                        locale={{
                            emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                        }} />
                </Modal>
            </div >
        );
    }
}

ProductCategorySelectPanel.propTypes = {
    onSelect: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object,
    value: PropTypes.object
};

export default injectIntl(ProductCategorySelectPanel);
